<script lang="ts" setup>
import { addClientService, clientListByPageService, deleteClientByIdService, editClientByIdService, getClientByIdService, getClientVipCountService } from "@/api/normal";
import { onMounted, reactive, ref } from "vue";
import { Search, Delete, Edit } from "@element-plus/icons-vue";

// 导航栏
import { ElMessage, type ComponentSize } from "element-plus";
const currentPage = ref(1); //当前页数
const pageSize = ref(7); //每页条数
const total = ref(100); //总条数

const size = ref<ComponentSize>("large");
const background = ref(true);
const disabled = ref(false);

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
};
const handleCurrentChange = (num) => {
  currentPage.value=num;
  clientListByPage();
};

//客户信息修改表单
const title=ref("");
const editFormVisible = ref(false)
import type { FormInstance, FormRules } from 'element-plus'

const ruleFormRef = ref<FormInstance>()


const validateName = (rule: any, value: any, callback: any) => {
  if (value=== '') {
    callback(new Error('姓名不能为空'))
  } else {
    callback()
  }
}
const validatePhone = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('手机号不能为空'))
  } else {
    callback()
  }
}

const ruleForm = ref({
  id:'',
  name: '',
  phone: '',
  money:''
})

const rules = ref<FormRules<typeof ruleForm>>({
  name: [{ validator: validateName, trigger: 'blur' }],
  phone: [{ validator: validatePhone, trigger: 'blur' }],
})


const clientData = ref([]); //客户表
const name = ref(""); //查询条件:姓名
const vip = ref(""); //查询条件:是否会员
const vipBtn1 = ref(); //会员用户开关
const vipBtn2 = ref(); //非会员用户开关

//条件分页获取客户信息列表
const clientListByPage = async () => {
  let params = {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    name: name.value ? name.value : null,
    vip: vip.value ? vip.value : null,
  };

  let result = await clientListByPageService(params);
  total.value = result.data.total;
  clientData.value = result.data.items;

  //处理数据
  for (let i = 0; i < clientData.value.length; i++) {
    let client = clientData.value[i];
    if (client.vip == 1) {
      client.vip = "会员";
    } else {
      client.vip = "非会员";
    }
  }
};
clientListByPage();

//根据id删除客户信息
const deleteClientById = async (id: any)=>{
  let result = await deleteClientByIdService(id);
  clientListByPage()
  ElMessage.success("删除成功")
}

//根据id获取客户信息
const getClientById=async (id:any)=>{
  let result= await getClientByIdService(id);
  ruleForm.value=result.data;
  ruleForm.value.money='';
}

//通过id对客户信息进行修改or充值
const editClientById=()=>{
  ruleFormRef.value.validate(async valid=>{
    if(valid){
      await editClientByIdService(ruleForm.value);
      //关闭窗口
      editFormVisible.value=false;
      //重新获取客户数据
      clientListByPage();
      ElMessage.success("修改成功")
    }else{
      ElMessage.error("请按规范填写信息")
    }

  })
}

//重置按钮事件
const reset=()=>{
  vipBtn1.value=false
  vipBtn2.value=false
  name.value=''
  clientListByPage()
}

//添加按钮事件
const addFormVisible=()=>{
  //清空表单数据
  ruleForm.value={
  id:'',
  name: '',
  phone: '',
  money:''
}
  //打开表单
  editFormVisible.value=true
}

//添加客户信息事件
const addClient=async ()=>{
  await addClientService(ruleForm.value);
  ElMessage.success("新增成功");
  //关闭窗口
  editFormVisible.value=false;
  //重新获取数据列表
  clientListByPage()
}




//客户会员占比饼状图
import * as echarts from "echarts";
const charts = ref();
onMounted(async () => {
  //调用接口，//获取客户的会员与非会员数据
  let result = await getClientVipCountService();
  let vips = [
    { value: result.data.vipYes, name: "会员" },
    { value: result.data.vipNo, name: "非会员" },
  ];

  //创建echarts实例
  const myChart = echarts.init(charts.value);
  myChart.setOption({
    title: {
      text: "会员与非会员占比情况",
      left: "center",
    },
    tooltip: {
      trigger: "item",
    },
    series: [
      {
        type: "pie",
        radius: "70%",
        data: vips,
      },
    ],
    emphasis: {
      itemStyle: {
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: "rgba(0, 0, 0, 1)",
      },
    },
  });
});
</script>

<template>
  <div style="display: flex">
    <el-card style="min-width: 750px; height: 500px">
      <el-switch
        v-model="vipBtn1"
        size="large"
        active-text=":会员用户"
        @change="
          vipBtn2 = false;
          vipBtn1 == false ? (vip = null) : (vip = '1');
          clientListByPage();
        "
      />&nbsp;&nbsp;&nbsp;
      <el-switch
        v-model="vipBtn2"
        size="large"
        active-text=":非会员用户"
        @change="
          vipBtn1 = false;
          vipBtn2 == false ? (vip = null) : (vip = '0');
          clientListByPage();
        "
      />&nbsp;&nbsp;&nbsp;
      <el-input
        v-model="name"
        style="width: 180px"
        placeholder="输入想要查询姓名"
        @input="clientListByPage()"
      />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <el-button type="info" @click="reset">重置</el-button>
      <el-button
        type="primary"
        @click="
          title = '添加客户信息';
          addFormVisible();
        "
        >添加</el-button
      >
      <el-table :data="clientData" stripe style="width: 100%; height: 400px">
        <el-table-column prop="name" label="姓名" width="144" />
        <el-table-column prop="phone" label="手机号" width="144" />
        <el-table-column prop="money" label="余额" width="144" />
        <el-table-column prop="vip" label="是否会员" width="144" />
        <el-table-column label="操作" width="144">
          <template #default="{ row }">
            <el-button
              :icon="Edit"
              circle
              plain
              type="primary"
              @click="
                title = '客户信息修改';
                getClientById(row.id);
                editFormVisible = true;
              "
            ></el-button>
            <el-popconfirm
              title="确定要删除该用户信息？"
              @cancel="ElMessage('您取消了删除')"
              @confirm="deleteClientById(row.id)"
            >
              <template #reference>
                <el-button :icon="Delete" circle plain type="danger"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 导航栏 -->
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <div ref="charts" style="min-width: 600px; height: 400px"></div>
  </div>

  <!-- 客户信息修改表单 -->
  <el-dialog v-model="editFormVisible" :title="title" width="500">
    <el-form :model="ruleForm"> </el-form>
    <template #footer>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="姓名：" prop="name">
          <el-input v-model="ruleForm.name" autocomplete="off" style="width: 200px" />
        </el-form-item>
        <el-form-item label="手机号：" prop="phone">
          <el-input v-model="ruleForm.phone" autocomplete="off" style="width: 200px" />
        </el-form-item>
        <el-form-item :label="title == '客户信息修改' ? '充值：' : '余额：'">
          <el-input v-model="ruleForm.money" style="width: 200px" />
        </el-form-item>
        <el-form-item label="会员条件：">
          单次充值满1000，自动升级为永久会员
        </el-form-item>
      </el-form>

      <div class="dialog-footer">
        <el-button @click="editFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="title == '客户信息修改' ? editClientById() : addClient()"
        >
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
